import Vue from 'vue'
import VueRouter from 'vue-router'
import store from '@/store'
import * as hooks from './hooks'

let originPush = VueRouter.prototype.push //备份原push方法
let originReplace = VueRouter.prototype.replace //备份原push方法

VueRouter.prototype.push = function (location, resolve, reject) {
  if (resolve && reject) {
    //如果传了回调函数，直接使用
    originPush.call(this, location, resolve, reject)
  } else {
    //如果没有传回调函数，手动添加
    originPush.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}

VueRouter.prototype.replace = function (location, resolve, reject) {
  if (resolve && reject) {
    //如果传了回调函数，直接使用
    originReplace.call(this, location, resolve, reject)
  } else {
    //如果没有传回调函数，手动添加
    originReplace.call(
      this,
      location,
      () => {},
      () => {}
    )
  }
}

// import sys from './routes/sys'
// import dashoard from './routes/dashoard'

// webpack提供一个方法,可以帮我们去检索指定目录下面的文件,并且还可以导入进来
// require.context(相对路径,是否递归你指定的目录下面的子目录,正则来指定需要检索的文件类型)
// const moduleFn = require.context('./routes', false, /\.js$/i)
// const children = moduleFn.keys().reduce((prev, path) => {
//   const value = moduleFn(path).default
//   if (Array.isArray(value)) {
//     prev.push(...value)
//   } else {
//     prev.push(value)
//   }
//   return prev
// }, [])

Vue.use(VueRouter)

// 定义路由规则表
const routes = [
  {
    path: '/login',
    component: () => import('@/views/login'),
    meta: {
      nologin: true
    }
  },
  {
    path: '/',
    name: 'admin',
    component: () => import('@/views/admin'),
    redirect: '/dashoard',
    // children: [...sys, ...dashoard]
    // children
  }
]

const router = new VueRouter({
  mode: 'history',
  // 访问当前应用地址它的前缀 / ==> http://xx.com/login
  // /aa => http://xx.com/aa/login
  base: '/',
  routes
})

// 动态添加新路由  router.addRoute(父路由name,路由规则)
// 参数1：父路由的路由name名称
// 参数2：路由规则，它是一个对象{path,component}
// router.addRoute('admin', {
//   path: '/film/add',
//   component: () => import('@/views/filmAdd'),
//   meta: {
//     breadcrumb: [{ to: '/dashoard', name: '首页' }, { name: '电影管理' }, { name: '新增电影' }]
//   }
// })

// hooks，全局前置守卫
for (let key in hooks) {
  router.beforeEach(hooks[key](store))
}

export default router
